#include "md5sum.h"

//Fonctions locales
static u_char *MDFile(FILE *f);
static u_char *MDFile_block(FILE *f, int begin, int end);


/**
 *
 */
u_char *MD5sum(const char *filepath)
{
	FILE *f;
	if ((f = fopen (filepath, "r")) == NULL)
		perror ("md5sum");
	else{
		u_char *key = MDFile(f);
		fclose(f);
		return key;
	}
	return NULL;
}

/**
 *
 */
u_char *MD5sum_block(const char *filepath, int begin, int end)
{
	FILE *f;
	if ((f = fopen (filepath, "r")) == NULL)
		perror ("md5sum_block");
	else {
		u_char *key = MDFile_block(f, begin, end);
		fclose(f);
		return key;
	}

	return NULL;
}


/**
 *
 */
u_char *getKeyHexa(u_char *md5sum){
	char *key = NULL;
	int ret = asprintf(&key,"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
			md5sum[0],md5sum[1],md5sum[2],md5sum[3],md5sum[4],md5sum[5],
			md5sum[6],md5sum[7],md5sum[8],md5sum[9],md5sum[10],md5sum[11],
			md5sum[12],md5sum[13],md5sum[14],md5sum[15]);
	strcat(key,"\0");

	if (ret == -1)
		return NULL;
	return key;
}



/**
 *
 */
static u_char *MDFile(FILE *f)
{
	struct md5_ctx ctx;
	u_char *digest = malloc(16);

	md5_init(&ctx);

	while (!feof (f)) {
		ctx.size += fread (ctx.buf + ctx.size, sizeof(char), MD5_BUFFER - ctx.size, f);
		md5_update(&ctx);
	}
	md5_final(digest, &ctx);
	return digest;
}


/**
 *
 */
static u_char *MDFile_block(FILE *f, int begin, int end)
{
	struct md5_ctx ctx;
	u_char *digest = malloc(16);
	int total_size;

	md5_init(&ctx);
	fseek(f, begin, SEEK_SET);

	while (total_size < end) {
		ctx.size += fread (ctx.buf + ctx.size, 1, MD5_BUFFER - ctx.size, f);
		total_size += ctx.size;
		md5_update(&ctx);
	}
	md5_final(digest, &ctx);
	return digest;
}
